package com.qianfeng.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianfeng.common.Constants;
import com.qianfeng.entity.dto.Goods;
import com.qianfeng.entity.dto.GoodsSku;
import com.qianfeng.entity.dto.Order;
import com.qianfeng.entity.vo.MyPage;
import com.qianfeng.mapper.OrderMapper;
import com.qianfeng.utils.MyUtils;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrderService extends ServiceImpl<OrderMapper , Order> {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsSkuService goodsSkuService;

    @Transactional
    public void saveOrder(Order order, Long loginMerchantId) {

        GoodsSku goodsSku = goodsSkuService.getById(order.getSkuId());
        Long totalPrice = Long.parseLong(goodsSku.getPrice()) * order.getNum();

        order.setTotalPrice(totalPrice);
        order.setMerchantId(loginMerchantId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String orderId = String.format("%s%s", sdf.format(new Date()), loginMerchantId);
        order.setOrderId(orderId);
        order.setPayState(0L);
        this.save(order);

    }

    @Transactional(readOnly = true)
    public MyPage<Order> getByMerchantId(Long merchantId , Long pageNum) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Order::getMerchantId, merchantId);

        IPage<Order> page = this.page(new Page<>(pageNum, Constants.PAGE_SIZE), wrapper);
        MyPage<Order> myPage = MyUtils.getMyPage(page);

        return myPage;
    }

    @Transactional(readOnly = true)
    public int getCountByGoodsId(Long goodsId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Order::getGoodsId , goodsId);
        return this.count(wrapper);
    }
}
